package dbUtils

import (
	"github.com/go-xorm/xorm"
	"xorm.io/core"
)

type DbWrapper struct {
	engine         *xorm.Engine
	Session        *xorm.Session
	Dbkey          string
	Prefix         string
	useTransaction bool
}

func (dao *DbWrapper) GetDbHelper() *xorm.Engine {
	if dao.engine != nil {
		return dao.engine
	}
	var db *xorm.Engine
	if dao.Dbkey == "" {
		db = NewDbHelper().GetWriteDb()
	} else {
		db = NewDbHelper().GetDbByKey(dao.Dbkey)
	}
	if dao.Prefix != "" {
		tbMapper := core.NewPrefixMapper(core.SameMapper{}, dao.Prefix)
		db.SetTableMapper(tbMapper)
	}
	dao.engine = db
	return db
}

func (dao *DbWrapper) getDbSession() *xorm.Session {
	if dao.Session != nil {
		if dao.Session.IsClosed() {
			dao.Session = dao.GetDbHelper().NewSession()
		}
		return dao.Session
	}
	dao.Session = dao.GetDbHelper().NewSession()
	return dao.Session
}

func (dao *DbWrapper) Find(beans interface{}, condiBeans ...interface{}) error {
	if dao.useTransaction {
		return dao.getDbSession().Find(beans,condiBeans)
	} else {
		return dao.GetDbHelper().Find(beans,condiBeans)
	}
}
